package com.bugstack.domain.strategy.service.rule.chain.impl;

import com.bugstack.domain.strategy.repository.IStrategyRepository;
import com.bugstack.domain.strategy.service.armory.IStrategyDispatch;
import com.bugstack.domain.strategy.service.rule.chain.AbstractLogicChain;
import com.bugstack.domain.strategy.service.rule.chain.factory.DefaultChainFactory;
import com.bugstack.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

/**
 * @Author: czb
 * @Description: 权重责任链
 * @DateTime: 2025/3/9 21:40
 **/
@Component("rule_weight")
@Slf4j
public class WeightLogicChain extends AbstractLogicChain {

    @Resource
    private IStrategyRepository repository;

    @Resource
    private IStrategyDispatch dispatch;


    @Override
    public DefaultChainFactory.StrategyAwardVO logic(String userId, Long strategyId) throws ExecutionException, InterruptedException {
        String ruleModel = DefaultChainFactory.LogicModel.RULE_WEIGHT.getCode();
        log.info("抽奖责任链-权重开始 userId: {} strategyId: {} ruleModel: {}", userId, strategyId, ruleModel);
        
        String ruleValue = repository.queryStrategyRuleValue(strategyId, ruleModel);

        // 1. 根据用户ID查询用户抽奖消耗的积分值，本章节我们先写死为固定的值。后续需要从数据库中查询。
        Map<Long, String> ruleWeightMap = getRuleWeights(ruleValue);
        if (null == ruleWeightMap || ruleWeightMap.isEmpty()) {
            return null;
        }
        // 2. 转换Keys值，并默认排序
        ArrayList<Long> analyticalSortedKeys = new ArrayList<>(ruleWeightMap.keySet());
        Collections.sort(analyticalSortedKeys);

        Integer userScore = repository.queryActivityAccountTotalUseCount(userId, strategyId);
        //3.找出最小符合值
        Long nextValue = analyticalSortedKeys.stream().filter(key -> userScore >= key).findFirst().orElse(null);

        //4.权重抽奖
        if (nextValue != null) {
            Integer awardId = dispatch.getRandomAwardId(strategyId, ruleWeightMap.get(nextValue));
            log.info("抽奖责任链-权重接管 userId: {} strategyId: {} ruleModel: {} awardId: {}", userId, strategyId, ruleModel, awardId);
            return DefaultChainFactory.StrategyAwardVO.builder().awardId(awardId).logicModel(ruleModel).build();
        }
        // 5. 过滤其他责任链
        log.info("抽奖责任链-权重放行 userId: {} strategyId: {} ruleModel: {}", userId, strategyId, ruleModel);
        return next().logic(userId, strategyId);
    }
    

    private Map<Long, String> getRuleWeights(String ruleValue) {
        String[] ruleValueGroups = ruleValue.split(Constants.SPACE);
        Map<Long, String> resultMap = new HashMap<>(ruleValueGroups.length);
        for (String ruleValueGroup : ruleValueGroups) {
            // 检查输入是否为空
            if (ruleValueGroup == null || ruleValueGroup.isEmpty()) {
                return resultMap;
            }
            // 分割字符串以获取键和值
            String[] parts = ruleValueGroup.split(Constants.COLON);
            if (parts.length != 2) {
                throw new IllegalArgumentException("rule_weight rule_rule invalid input format" + ruleValueGroup);
            }
            //放入键值对
            resultMap.put(Long.parseLong(parts[0]), ruleValueGroup);
        }
        return resultMap;
    }
}
